<?php

namespace App\Console\Commands\WorkOrder;

use App\Enums\WorkOrder\OrderEnum;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Service\WorkOrder\Manager\ManagerService;
use App\Service\WorkOrder\Mission\MissionEngineService;
use Illuminate\Console\Command;

class TransferMission extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workOrder:transfer-mission {uid}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '任务转交';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $currentUid = (int)$this->argument('uid');
        if ($currentUid <= 0) {
            dd('uid不能为空');
        }

        WorkOrderApplyManagerModel::query()
                                  ->where('managerId', $currentUid)
                                  ->with('applyMainRel')
                                  ->where('status', WorkOrderApplyManagerModel::STATUS_ON)
                                  ->get()
                                  ->each(function ($item) use ($currentUid) {

                                      if (!$item->applyMainRel) {
                                          return;
                                      }

                                      if ($item->applyMainRel->status != OrderEnum::MAIN_STATUS_ING) {
                                          return;
                                      }

                                      $targetUid = ManagerService::popManagerId($item->role,
                                          $item->applyMainRel->problemPid, $item->applyMainRel->problemChildId, $currentUid);

                                      $this->info("{$item->workOrderNo}-{$item->managerId}-{$targetUid}");

                                      // 指派
                                      (new MissionEngineService($item->workOrderNo))->transfer($item->managerId, $targetUid, false);
                                  });
    }
}
